package controllers

import (
	"github.com/astaxie/beego"
	"anfang/models"
	"HTanfang/htmodels"
	"strconv"
	"time"
	"os"
	"strings"
	"github.com/astaxie/beego/validation"
)

type DevicesController struct {
	beego.Controller
}

//带了参数导致bootstrap table无法正常使用
func (c *DevicesController)HTDevicesList_html() {
	str_DeviceType := c.Ctx.Input.URL()[strings.LastIndex(c.Ctx.Input.URL(), "/") + 1:]
	DeviceType, _ := strconv.Atoi(str_DeviceType)
	c.Data["DeviceType"] = DeviceType
	c.TplName = "devices_list.html"
	c.Render()
}

func (c *DevicesController)HTDevicesList() {
	DeviceType, _ := c.GetInt("DeviceType")
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{ "Id", "DeviceName", "DeviceSN", "DeviceType", "DeviceStatus","DeviceCreateTime","DeviceUpdateTime", "DevicePosition"}
	Devices := []models.Devices{}
	htmodels.HTDevicesGetList(&Devices, fileds, DeviceType,  offset, limit, search, "DeviceName", orderby)
	count, _ := htmodels.HTDevicesGetCount(search, "DeviceName", DeviceType, )
	c.Data["json"] = map[string]interface{}{"rows":&Devices, "total":count}
	c.ServeJSON()
}


func (c *DevicesController)HTDevicesDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetDevicesDetailInfo(c, Id)
	}
	mytype,_:=c.GetInt("type")
	c.Data["Type"]=mytype
	c.TplName = "devices_detail.html"
}

func SetDevicesDetailInfo(c *DevicesController, Id int64) {
	Devices := models.Devices{Id:int(Id)}
	htmodels.HTDevicesGetDetail(&Devices)
	c.Data["Devices"] = &Devices
}

func (c *DevicesController)HTDevicesAdd() {
	Devices := models.Devices{}
	if err := c.ParseForm(&Devices); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("devicecreatetime"));err!=nil{
		Devices.DeviceCreateTime=time.Now()
	}else{
		Devices.DeviceCreateTime=time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("deviceupdatetime"));err!=nil{
		Devices.DeviceUpdateTime=time.Now()
	}else{
		Devices.DeviceUpdateTime=time_up
	}

	valide := validation.Validation{}
	if b, err := valide.Valid(&Devices); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTDevicesAdd(&Devices); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	path:="/var/uploads/anfang"
	url:= "uploads/Devices/DevicePic"
	if strings.Index(url, "?") != -1 {
		url = url[:strings.Index(url, "?")]
	}
	totalpath := path + url[strings.Index(url, "uploads") + len("uploads"):]
	GenerateTumbnail(totalpath, "Devices", int64(Devices.Id), 100, 100)
	Message(&c.Controller, `/devices/detail`, "添加成功！", "", false)
}


func (c *DevicesController)HTDevicesUpdate() {
	Id , _ := c.GetInt64("Id");
	Devices := models.Devices{Id:int(Id)}
	if err:=htmodels.HTDevicesGetDetail(&Devices);err!=nil{
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	if err := c.ParseForm(&Devices); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("devicecreatetime"));err!=nil{
		Devices.DeviceCreateTime=time.Now()
	}else{
		Devices.DeviceCreateTime=time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("deviceupdatetime"));err!=nil{
		Devices.DeviceUpdateTime=time.Now()
	}else{
		Devices.DeviceUpdateTime=time_up
	}

	valide := validation.Validation{}
	if b, err := valide.Valid(&Devices); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTDevicesUpdate(&Devices); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/devices/list_html`+`/`+strconv.Itoa(Devices.DeviceType), "更新成功！", "", false)
}


func (c *DevicesController)HTDevicesDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTDevicesDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}


//image upload
func (c *DevicesController)HTDevicesPicUp() {
	Id, _ := c.GetInt64("Id")
	_, h, err := c.GetFile("Filedata")
	if err != nil {
		Json_Message(&c.Controller, 1, "file upload error")
	}
	url := c.GetString("imagepath")
	totalpath := ""
	path := beego.AppConfig.String("uploadspath")
	if url == "" {
		typename := h.Filename[strings.LastIndex(h.Filename, "."):]
		date := time.Now().Format("2006-01-02")
		directory := "/devices/pics/" + date
		filename := RandString(8)
		totalpath = path + directory + "/" + filename + typename
		url = "/uploads" + directory + "/" + filename + typename
		os.MkdirAll(path + directory, 0777)
	} else {
		if strings.Index(url, "?") != -1 {
			url = url[:strings.Index(url, "?")]
		}
		totalpath = path + url[strings.Index(url, "uploads") + len("uploads"):]
	}

	if err := c.SaveToFile("Filedata", totalpath); err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	if Id != 0 {
		GenerateTumbnail(totalpath, "Devices", Id, 100, 100)
	}
	Json_Message(&c.Controller, 0, url + "?time=" + time.Now().String())
}

func (c *DevicesController)DeviceChar() {
	Id,_:=c.GetInt("Id")
	c.Data["Id"]=Id
	c.TplName="devicemessageChart.html"
}
